package com.booter.ws.config;

import com.booter.ws.config.response.HttpResponseOutStreamCopier;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author lcw
 * @date 2023/8/16 18:27
 */
@Slf4j
//@Order(1)
//@WebFilter(urlPatterns = "/*", filterName = "responseRewriteFilter")
public class ResponseRewriteFilter implements Filter {

    @Autowired
    private CloseableHttpClient httpClient;

    private final String tmpdir = System.getProperty("java.io.tmpdir");

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("init method");
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if (req.getRequestURI().equals("/test/upload") || req.getRequestURI().contains("/attach")) {
            chain.doFilter(request, response);
            return;
        }
        //response.getContentType()
        HttpResponseOutStreamCopier rw = new HttpResponseOutStreamCopier((HttpServletResponse) response);
        chain.doFilter(request, rw);
        String content = rw.getHeader("Content-disposition");
        if (StringUtils.isEmpty(content)) {
            //重新写入原输入流
            response.getOutputStream().write(rw.getByteArrayOutputStream().toByteArray());
            return;
        }
        HttpPost post = new HttpPost("http://localhost:8080/test/upload");

        File f = new File("/Users/lichunwen/Downloads/s_" + System.currentTimeMillis() + ".xlsx");
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
        out.write(rw.getByteArrayOutputStream().toByteArray());
        out.flush();
        out.close();
        rw.flush();

        MultipartEntityBuilder bu = MultipartEntityBuilder.create();
        bu.addBinaryBody("file", f);
        bu.addPart("user_email", new StringBody("lichunwen@xueqiu.com", ContentType.TEXT_PLAIN));
        bu.addPart("file_type", new StringBody("xlsx", ContentType.TEXT_PLAIN));
        bu.addPart("user_name", new StringBody("lichunwen", ContentType.TEXT_PLAIN));
        bu.addPart("level", new StringBody("1", ContentType.TEXT_PLAIN));
        bu.addPart("result_type", new StringBody("file", ContentType.TEXT_PLAIN));
        post.setEntity(bu.build());

//        post.setEntity(new ByteArrayEntity(rw.getByteArrayOutputStream().toByteArray()));
        //改写json输出
//          ApiModel model = new ApiModel(null, 0, null);
//                model.setMessage(xr.getMessage());
//                model.setResultCode(ErrorCode.WATER_MARK_ERROR.getErrorCode());
//                response.getOutputStream().write(JSONUtil.toJSON(model).getBytes(StandardCharsets.UTF_8));
//                response.setContentType("application/json;charset=utf-8");

        try (CloseableHttpResponse execute = httpClient.execute(post)) {
            if (execute.getStatusLine().getStatusCode() != HttpStatus.OK.value()) {
                response.getOutputStream().write(rw.getByteArrayOutputStream().toByteArray());
                return;
            } else {
                //重新写入输入流
                response.getOutputStream().write(EntityUtils.toByteArray(execute.getEntity()));
                execute.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            f.delete();
        }


    }


    @Override
    public void destroy() {

    }
}